import SplashComponent from "@components/Splash/SplashComponent";
import AppSettings from "@runtime/base/AppSettings";
import { ClientMessage } from "@runtime/generate/message/ClientMessage";
import WebSocketComponent from "@runtime/module/WebSocket/WebSocketComponent";
import AssetLoaderComponent from "@runtime/UnityEngineBridge/AssetLoaderComponent";
import { Ref, ref, WatchStopHandle } from "@vue/runtime-dom";
import installContent from "./installMenu/installMenu";
import MessageCode from "./MessageCode";

/**
 * 起始页
 */
export default class HomeContent {
    private static instance: HomeContent = new HomeContent();
    /**
     * 起始页
     */
    public static get Default(): HomeContent {
        return this.instance;
    }

    constructor() {
        window.addEventListener('unload', this.Dispose.bind(this));
    }

    Dispose() {
        window.removeEventListener('unload', this.Dispose);

        for (const watchStopHandle of this.watchStopHandles) {
            watchStopHandle();
        }
        this.watchStopHandles.clear();
    }
    
    public ProductName: Ref<any> = ref()

    public TypeStatus: Ref<boolean> = ref(false);
    public ApplicationType: Ref<string> = ref('');

    public Loaded: Ref<boolean> = ref(false);

    public ProgressText: Ref<string> = ref('');
    public ProgressVal: Ref<number> = ref(0);

    // public MultimeterData: Ref<ClientMessage.StructureCognitionResponse> = ref(new ClientMessage.StructureCognitionResponse)

    // 语音控制
    public VoiceControl: Ref<boolean> = ref(true);
    public pausableType: Ref<any> = ref({ pausable: true });
    public endplay: Ref<any> = ref({ ended: true });


    private watchStopHandles: Array<WatchStopHandle> = [];
    //操作类型
    //项目类型
    public itemType: Ref<string> = ref('');

    //项目数据
    public ProjectData: Ref<Array<any>> = ref([]);

    //鼠标标签内容
    public MouseLabel: Ref<string> = ref('');
    public MouseLabelX: Ref<string> = ref('0');
    public MouseLabelY: Ref<string> = ref('0');
    //工具栏信息
    public ToolInformation: Ref<any> = ref({});
    public Tool_Icon: Ref<any> = ref('');
    //当前ID
    public IDCorrente: Ref<number> = ref(0);
    //提示
    public pointOut: Ref<any> = ref('');
    public pointOutTypes: Ref<number> = ref(0);

    public OnReceive(id: number, content: string): void {
        // console.log(`${id} - ${content}`);
        if (this.IsJsonString(content)) {
            if (id == MessageCode.Default.MsgCodesList.SYSTEM_LABEL) {
                this.MouseLabel.value = JSON.parse(content).Result
            }
            if (id == MessageCode.Default.MsgCodesList.TOOL_BAR_UPDATE) {
                this.ToolInformation.value = JSON.parse(content).Result
                this.Tool_Icon.value = '/structure/' + JSON.parse(content).Result.Icon + '.png'
            }
            if (id == MessageCode.Default.MsgCodesList.DISASSEMBLY_STEP_SELECT) {
                this.IDCorrente.value = JSON.parse(content).Result
            }
            if (id == MessageCode.Default.MsgCodesList.DISASSEMBLY_STEP_COMPLETE) {
                installContent.Default.InstallProData.value = JSON.parse(content).Result
            }
            if (id == MessageCode.Default.MsgCodesList.SYSTEM_WARNING) {
                this.pointOut.value = JSON.parse(content).Result
                this.pointOutTypes.value++
            }
        }
    }
    public Calibration(id: number, content: string): void {
        // console.log(`${id} - ${content}`);
        if (this.IsJsonString(content)) {
            if (id == MessageCode.Default.MsgCodesList.SYSTEM_LABEL) {
                this.MouseLabel.value = JSON.parse(content).Result
            }
            if (id == MessageCode.Default.MsgCodesList.TOOL_BAR_UPDATE) {
                this.ToolInformation.value = JSON.parse(content).Result
                this.Tool_Icon.value = '/structure/' + JSON.parse(content).Result.Icon + '.png'
            }
            if (id == MessageCode.Default.MsgCodesList.DISASSEMBLY_STEP_SELECT) {
                this.IDCorrente.value = JSON.parse(content).Result
            }
            if (id == MessageCode.Default.MsgCodesList.DISASSEMBLY_STEP_COMPLETE) {
                installContent.Default.InstallProData.value = JSON.parse(content).Result
            }
            if (id == MessageCode.Default.MsgCodesList.SYSTEM_WARNING) {
                this.pointOut.value = JSON.parse(content).Result
                this.pointOutTypes.value++
            }
        }
    }

    //工单显隐
    public WorkOrderShow: Ref<boolean> = ref(false);
    public toolrShow: Ref<boolean> = ref(false);


    //判断类型
    IsJsonString(str: any) {
        try {
            JSON.parse(str);
        } catch (e) {
            return false;
        }
        return true;
    }

    public async Awake(Name:any): Promise<void> {
        this.Loaded.value = true;
        this.ProgressText.value = '渲染引擎初始化'
        this.ProgressVal.value = 90

        // 启动Unity
        // 资源编号R00043
        // 拆装
        const configuration = JSON.stringify({
            LocalAddress: AppSettings.Default.LocalAddress,
            // ShortName: 'P10064',
            ShortName: Name,
            Type: 1001,
        });

        await WebSocketComponent.Default.PostMessageAsync(new ClientMessage.EmbeddedApplicationLaunchRequest('../EmbeddedApplication/Unity/Mix.Unity.exe', configuration));

        setTimeout(async () => {
            this.ProgressText.value = '环境模块初始化'
            this.ProgressVal.value = 75
        }, 800);

        // // 获取Unity版本状态
        await WebSocketComponent.Default.PostMessageAsync(new ClientMessage.EmbeddedApplicationVersionRequest());
        setTimeout(async () => {
            this.ProgressText.value = '相机模块初始化'
            this.ProgressVal.value = 55
        }, 1600);

        if (HomeContent.Default.ApplicationType.value == '标定') {
            let newArr: any = await WebSocketComponent.Default.PostMessageAsync(new ClientMessage.CalibrationAdapterRequest(MessageCode.Default.MsgCodesList.SYSTEM_GET_ASSET))
            let AssetList: any[] = []
            JSON.parse(newArr.Content).Result.forEach((item: any) => {
                AssetList.push(item.Asset)
            });
            await AssetLoaderComponent.Default.LoadAllAsync(AssetList);

        } else if (HomeContent.Default.ApplicationType.value == '拆装') {
            let newArr: any = await WebSocketComponent.Default.PostMessageAsync(new ClientMessage.DisassemblyAdapterRequest(MessageCode.Default.MsgCodesList.SYSTEM_GET_ASSET))
            // let newArr: any = await WebSocketComponent.Default.PostMessageAsync(new ClientMessage.SystemAdapterRequest(MessageCode.Default.MsgCodesList.SYSTEM_GET_ASSET))
            let AssetList: any[] = []
            JSON.parse(newArr.Content).Result.forEach((item: any) => {
                AssetList.push(item.Asset)
            });
            await AssetLoaderComponent.Default.LoadAllAsync(AssetList);
        }

    }
    
    public async StrAwake(Name:any): Promise<void> {
        this.Loaded.value = true;
        this.ProgressText.value = '渲染引擎初始化'
        this.ProgressVal.value = 85

        // 启动Unity
        // 资源编号R00042
        // 解构
        const configuration = JSON.stringify({
            LocalAddress: AppSettings.Default.LocalAddress,
            // ShortName: 'P10064',
            ShortName: Name,
            Type: 1000,
        });
        console.log('configuration',configuration);
        await WebSocketComponent.Default.PostMessageAsync(new ClientMessage.EmbeddedApplicationLaunchRequest('../EmbeddedApplication/Unity/Mix.Unity.exe', configuration));
        setTimeout(async () => {
            this.ProgressText.value = '环境模块初始化'
            this.ProgressVal.value = 70
        }, 800);
        // // 获取Unity版本状态
        await WebSocketComponent.Default.PostMessageAsync(new ClientMessage.EmbeddedApplicationVersionRequest());
        setTimeout(async () => {
            this.ProgressText.value = '相机模块初始化'
            this.ProgressVal.value = 45
        }, 1600);
    }

    public async Destroy(): Promise<void> {
    }
}